<template>
  <div class="identity-container">
    <!-- 顶部导航栏 -->
    <div class="identity-header">
      <div class="back-button" @click="goBack">
        <el-icon><ArrowLeft /></el-icon>
      </div>
      <div class="header-title">基本信息</div>
      <div class="placeholder"></div>
    </div>
    
    <!-- 提示信息 -->
    <div class="identity-tip">
      填写真实有效的信息，审核才会通过~
    </div>
    
    <!-- 表单区域 -->
    <div class="identity-form">
      <!-- 姓名 -->
      <div class="form-item horizontal">
        <div class="form-label">姓名</div>
        <div class="form-input">
          <el-input v-model="formData.name" placeholder="请输入您的真实姓名" clearable />
        </div>
      </div>
      
      <!-- 身份证号 -->
      <div class="form-item horizontal">
        <div class="form-label">身份证号</div>
        <div class="form-input">
          <el-input v-model="formData.idNumber" placeholder="请输入您的身份证号码" clearable />
        </div>
      </div>
      
      <!-- 身份证照片上传区域 -->
      <div class="upload-section">
        <div class="upload-tip">*您本人身份证，且内容清晰可辨</div>
        <div class="upload-tip">请确认拍摄的照片边缘完整</div>
        
        <!-- 身份证正面 -->
        <div class="upload-item">
          <div class="upload-box" @click="triggerUpload('front')">
            <div v-if="!formData.frontImage && !formData.frontImageUrl" class="upload-placeholder">
              <el-icon class="upload-icon"><Camera /></el-icon>
              <div class="upload-text">身份证正面照片上传</div>
            </div>
            <img v-else-if="formData.frontImageUrl" :src="formData.frontImageUrl" class="preview-image" />
            <img v-else :src="formData.frontImage" class="preview-image" />
            <div v-if="uploading" class="upload-loading">
              <el-icon class="is-loading"><Loading /></el-icon>
              <span>上传中...</span>
            </div>
          </div>
          <input
            ref="frontImageInput"
            type="file"
            accept="image/*"
            class="file-input"
            @change="handleImageUpload('front', $event)"
          />
        </div>
        
        <!-- 身份证反面 -->
        <div class="upload-item">
          <div class="upload-box" @click="triggerUpload('back')">
            <div v-if="!formData.backImage && !formData.backImageUrl" class="upload-placeholder">
              <el-icon class="upload-icon"><Camera /></el-icon>
              <div class="upload-text">身份证反面照片上传</div>
            </div>
            <img v-else-if="formData.backImageUrl" :src="formData.backImageUrl" class="preview-image" />
            <img v-else :src="formData.backImage" class="preview-image" />
            <div v-if="uploading" class="upload-loading">
              <el-icon class="is-loading"><Loading /></el-icon>
              <span>上传中...</span>
            </div>
          </div>
          <input
            ref="backImageInput"
            type="file"
            accept="image/*"
            class="file-input"
            @change="handleImageUpload('back', $event)"
          />
        </div>
        
        <!-- 手持身份证 -->
        <div class="upload-item">
          <div class="upload-box" @click="triggerUpload('holding')">
            <div v-if="!formData.holdingImage && !formData.holdingImageUrl" class="upload-placeholder">
              <el-icon class="upload-icon"><Camera /></el-icon>
              <div class="upload-text">手持身份证照片上传</div>
            </div>
            <img v-else-if="formData.holdingImageUrl" :src="formData.holdingImageUrl" class="preview-image" />
            <img v-else :src="formData.holdingImage" class="preview-image" />
            <div v-if="uploading" class="upload-loading">
              <el-icon class="is-loading"><Loading /></el-icon>
              <span>上传中...</span>
            </div>
          </div>
          <input
            ref="holdingImageInput"
            type="file"
            accept="image/*"
            class="file-input"
            @change="handleImageUpload('holding', $event)"
          />
        </div>
      </div>
    </div>
    
    <!-- 提交按钮 -->
    <div class="submit-button-container">
      <el-button type="primary" class="submit-button" @click="submitForm">提交</el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
import { ArrowLeft, Camera, Loading } from '@element-plus/icons-vue'
import { useUserStore, useUserInfoStore } from '@/store'
import userService from '@/services/userService'

const router = useRouter()
const userStore = useUserStore()
const userInfoStore = useUserInfoStore()

// 表单数据
const formData = reactive({
  name: '',
  idNumber: '',
  frontImage: '',
  backImage: '',
  holdingImage: '',
  // 存储上传后的图片URL
  frontImageUrl: '',
  backImageUrl: '',
  holdingImageUrl: ''
})

// 文件输入引用
const frontImageInput = ref(null)
const backImageInput = ref(null)
const holdingImageInput = ref(null)

// 加载状态
const uploading = ref(false)

// 初始化数据
onMounted(() => {
  if (userInfoStore.state.isLoaded) {
    // 如果已经加载了用户信息，则填充表单
    formData.name = userInfoStore.state.detailInfo.name || ''
    formData.idNumber = userInfoStore.state.basicInfo.idCard || ''
    
    // 如果已有图片URL，则显示图片
    if (userInfoStore.state.detailInfo.idCardFrontImage) {
      formData.frontImageUrl = userInfoStore.state.detailInfo.idCardFrontImage
      formData.frontImage = userInfoStore.state.detailInfo.idCardFrontImage
    }
    
    if (userInfoStore.state.detailInfo.idCardBackImage) {
      formData.backImageUrl = userInfoStore.state.detailInfo.idCardBackImage
      formData.backImage = userInfoStore.state.detailInfo.idCardBackImage
    }
    
    if (userInfoStore.state.detailInfo.idCardHandImage) {
      formData.holdingImageUrl = userInfoStore.state.detailInfo.idCardHandImage
      formData.holdingImage = userInfoStore.state.detailInfo.idCardHandImage
    }
  }
})

// 返回上一页
const goBack = () => {
  router.back()
}

// 触发文件上传
const triggerUpload = (type) => {
  switch (type) {
    case 'front':
      frontImageInput.value.click()
      break
    case 'back':
      backImageInput.value.click()
      break
    case 'holding':
      holdingImageInput.value.click()
      break
  }
}

// 处理图片上传
const handleImageUpload = async (type, event) => {
  const file = event.target.files[0]
  if (!file) return
  
  // 验证文件类型
  if (!file.type.includes('image/')) {
    ElMessage.error('请上传图片文件')
    return
  }
  
  // 验证文件大小（限制为5MB）
  if (file.size > 5 * 1024 * 1024) {
    ElMessage.error('图片大小不能超过5MB')
    return
  }
  
  // 读取文件并预览
  const reader = new FileReader()
  reader.onload = async (e) => {
    // 设置预览图片
    switch (type) {
      case 'front':
        formData.frontImage = e.target.result
        break
      case 'back':
        formData.backImage = e.target.result
        break
      case 'holding':
        formData.holdingImage = e.target.result
        break
    }
    
    // 上传图片到服务器
    try {
      uploading.value = true
      
      // 根据类型确定上传的fileType参数
      let fileType = 'other'
      switch (type) {
        case 'front':
          fileType = 'idCardFront'
          break
        case 'back':
          fileType = 'idCardBack'
          break
        case 'holding':
          fileType = 'idCardHand'
          break
      }
      // 调用上传API
      const response = userService.uploadFile(userStore.userId, file, fileType)
      if (response) {
        // 保存上传后的图片URL
        switch (type) {
          case 'front':
            formData.frontImageUrl = response.fileUrl
            break
          case 'back':
            formData.backImageUrl = response.fileUrl
            break
          case 'holding':
            formData.holdingImageUrl = response.fileUrl
            break
        }
      }
    }finally {
      uploading.value = false
    }
  }
  reader.readAsDataURL(file)
}

// 验证身份证号
const validateIdNumber = (idNumber) => {
  const reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/
  return reg.test(idNumber)
}

// 验证表单
const validateForm = () => {
  if (!formData.name.trim()) {
    ElMessage.error('请输入姓名')
    return false
  }
  
  if (!formData.idNumber.trim()) {
    ElMessage.error('请输入身份证号')
    return false
  }
  
  if (!validateIdNumber(formData.idNumber)) {
    ElMessage.error('请输入有效的身份证号')
    return false
  }
  
  if (!formData.frontImage && !formData.frontImageUrl) {
    ElMessage.error('请上传身份证正面照片')
    return false
  }
  
  if (!formData.backImage && !formData.backImageUrl) {
    ElMessage.error('请上传身份证反面照片')
    return false
  }
  
  if (!formData.holdingImage && !formData.holdingImageUrl) {
    ElMessage.error('请上传手持身份证照片')
    return false
  }
  
  // 检查是否所有图片都已上传到服务器
  if (formData.frontImage && !formData.frontImageUrl) {
    ElMessage.error('身份证正面照片正在上传中，请稍候')
    return false
  }
  
  if (formData.backImage && !formData.backImageUrl) {
    ElMessage.error('身份证反面照片正在上传中，请稍候')
    return false
  }
  
  if (formData.holdingImage && !formData.holdingImageUrl) {
    ElMessage.error('手持身份证照片正在上传中，请稍候')
    return false
  }
  
  return true
}

// 提交表单
const submitForm = async () => {
  if (!validateForm()) return

  // 准备用户数据
  const userData = {
    id: userStore.userId,
    name: formData.name,
    idCard: formData.idNumber,
    idCardFrontImage: formData.frontImageUrl,
    idCardBackImage: formData.backImageUrl,
    idCardHandImage: formData.holdingImageUrl
  }

  // 调用API更新用户信息
  userService.updateUserInfoAndReturn(userData)
  // 返回个人资料页
  router.push('/user/profile')
}
</script>

<style scoped>
.identity-container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background-color: #f5f7fa;
}

/* 顶部导航栏样式 */
.identity-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 50px;
  background-color: #3a4a6d;
  color: white;
  padding: 0 15px;
}

.back-button {
  font-size: 20px;
  cursor: pointer;
}

.header-title {
  font-size: 18px;
  font-weight: 500;
}

.placeholder {
  width: 20px;
}

/* 提示信息样式 */
.identity-tip {
  background-color: #f0f0f0;
  padding: 10px 15px;
  font-size: 14px;
  color: #666;
}

/* 表单区域样式 */
.identity-form {
  margin-top: 10px;
  background-color: white;
  padding: 15px;
}

.form-item {
  margin-bottom: 15px;
}

.form-item.horizontal {
  display: flex;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid #f0f0f0;
}

.form-label {
  font-size: 16px;
  color: #333;
  margin-bottom: 8px;
}

.form-item.horizontal .form-label {
  width: 120px;
  flex-shrink: 0;
  margin-bottom: 0;
  padding-right: 15px;
  color: #606266;
  font-size: 14px;
}

.form-value {
  font-size: 16px;
  color: #666;
  text-align: right;
}

.form-input {
  width: 100%;
}

.form-item.horizontal .form-input {
  flex: 1;
}

/* 上传区域样式 */
.upload-section {
  margin-top: 20px;
}

.upload-tip {
  font-size: 14px;
  color: #909399;
  margin-bottom: 5px;
  padding-left: 5px;
}

.upload-item {
  margin-top: 15px;
  position: relative;
}

.upload-box {
  width: 100%;
  height: 150px;
  border: 1px dashed #d9d9d9;
  border-radius: 4px;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  overflow: hidden;
}

.upload-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.upload-icon {
  font-size: 40px;
  color: #8c939d;
}

.upload-text {
  margin-top: 10px;
  font-size: 14px;
  color: #8c939d;
}

.file-input {
  display: none;
}

.preview-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.upload-loading {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-color: rgba(0, 0, 0, 0.5);
  color: white;
  font-size: 14px;
}

.upload-loading .is-loading {
  font-size: 24px;
  margin-bottom: 8px;
  animation: rotating 2s linear infinite;
}

@keyframes rotating {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

/* 提交按钮样式 */
.submit-button-container {
  padding: 20px 15px;
  margin-top: auto;
}

.submit-button {
  width: 100%;
  height: 44px;
  font-size: 16px;
  border-radius: 4px;
  background-color: #3a4a6d;
  border-color: #3a4a6d;
}
</style>